13. Handling Errors
Handling Errors Try Except Finally
Try Statement
We can use try statements to handle exceptions. There are four clauses you can use (one more in addition to those shown in the video).
- try: This is the only mandatory clause in a- trystatement. The code in this block is the first thing that Python runs in a- trystatement.
- except: If Python runs into an exception while running the- tryblock, it will jump to the- exceptblock that handles that exception.
- else: If Python runs into no exceptions while running the- tryblock, it will run the code in this block after running the- tryblock.
- finally: Before Python leaves this- trystatement, it will run the code in this- finallyblock under any conditions, even if it's ending the program. E.g., if Python ran into an error while running code in the- exceptor- elseblock, this- finallyblock will still be executed before stopping the program.
Handling Error Specifying Exceptions
Specifying Exceptions
We can actually specify which error we want to handle in an except block like this:
try:
    # some code
except ValueError:
    # some codeNow, it catches the ValueError exception, but not other exceptions. If we want this handler to address more than one type of exception, we can include a parenthesized tuple after the except with the exceptions.
try:
    # some code
except (ValueError, KeyboardInterrupt):
    # some codeOr, if we want to execute different blocks of code depending on the exception, you can have multiple except blocks.
try:
    # some code
except ValueError:
    # some code
except KeyboardInterrupt:
    # some code